<template>
  <base-container :footer="isActivated" is-template :show-title="false" :footerH="true">
    <base-container>
      <QueryFieldsHJBW
        ref="QueryFieldsRef"
        v-model:type="type"
        v-model:bw="BwFormFields"
        v-model:cibao="CiBaoFormFields"
        v-model:get-result="getResult"
        v-model:HjbwFormFields="HJBWFormFields"
        :package-list="packageList"
        :submitting="loading"
        :bw-submitting="bwSearching"
        :LandingPageList="LandingPageList"
        :combo-price-list="comboPriceList"
        :combo-price-loading="comboPriceLoading"
        :code="code"
        @cibao-submit="loadKeywordList"
        @cibao-reset="handleCiBaoReset"
        @cibao-package-change="handlePackageChange"
        @hjbw-submit="hjbwLoadKeywordList"
        @bw-submit="handleBwSearcher"
        @bw-reset="handleBwReset"
        @bw-jiekshuj="handleBwResetiusid"
        @platform-ids-change="handlePlatformIdsChange"
      />

      <div v-show="CiBao || CBYXB">
        <!--      <div v-show="CiBao || CBYXB || CBTEH || DFTEH">-->
        <Divider />
        <table-toolbar>
          <span class="ml-2">推广区域：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">全国</a-tag>
          <!-- <span class="ml-2">最快开始投放时间：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ releaseRange }}
          </a-tag> -->
          <template #bar-left>
            <div>
              <span class="font-bold ft-16">推广关键词</span>
              <ForbiddenText :category="type" />
            </div>
          </template>
        </table-toolbar>
        <a-row :gutter="16">
          <a-col :span="12">
            <KeywordTable
              :loading="keywordLoading"
              :max-length="currentPackage?.wordsNumTotal ?? 0"
              :type="type"
              :comboId="CiBaoFormFields.packageId"
              v-model:keyword-table-data="keywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
          <a-col :span="12">
            <SelectedTable
              v-model:raw-keyword-table-data="rawKeywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
        </a-row>
        <!--<a-alert type="success" class="mt-5">
          <template #message>
            1.近日百度流量接口出现不稳定情况，导致前端查价出现报错或者不出现推荐关键词的情况，技术已经紧急处理，预计2-3个工作日；<br />
            2.遇到此种情况可以尝试多次点击“查询”触发接口，一般3-5次可以出查询结果。给您带来的不便还请谅解。
          </template>
        </a-alert>-->
      </div>
      <div v-show="HJBW">
        <Divider />
        <div style="display: flex">
          <a-form-item label="是否黄金展位转移" name="hzTransferCode" style="margin-top: 10px">
            <a-radio-group v-model:value="HJBWFormFields.hzTransferCode">
              <a-radio-button :value="1">是</a-radio-button>
              <!-- <a-radio-button :value="2">否</a-radio-button> -->
            </a-radio-group>
          </a-form-item>
          <a-form-item
            v-if="HJBWFormFields.hzTransferCode === IsFromHjzwEnum.Yes"
            label="转移备注"
            name="hzNotes"
            style="margin-top: 10px; margin-left: 20px"
          >
            <a-textarea
              style="width: 300px"
              :rows="1"
              v-model:value.trim="HJBWFormFields.hzNotes"
              placeholder="请输入转移公司名称！"
              allow-clear
            />
          </a-form-item>
        </div>
        <table-toolbar>
          <span class="ml-2">推广时长：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ HJBWFormFields.comboPriceName }}
          </a-tag>
          <span class="ml-2">投放时段：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ HJBWFormFields.onLinePeriod }}
          </a-tag>
          <span class="ml-2">最快开始投放时间4：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ releaseRange }}
          </a-tag>
          <template #bar-left>
            <div>
              <span class="font-bold ft-16">推广关键词</span>
              <ForbiddenText :category="type" />
              <span>（单个关键词长度至少4个字8个字符，一个汉字算两个字符，英文字母算一个字符）</span>
            </div>
          </template>
        </table-toolbar>
        <a-row :gutter="16">
          <a-col :span="12">
            <KeywordTable
              :loading="hjbwKeywordLoading"
              :type="type"
              v-model:keyword-table-data="hjbwKeywordTableData"
              v-model:selected-table-data="hjbwSelectedTableData"
            />
            <!-- :max-length="currentPackage?.wordsNumTotal ?? 0" -->
          </a-col>
          <a-col :span="12">
            <SelectedTable
              v-model:raw-keyword-table-data="rawKeywordTableDataHjbw"
              v-model:selected-table-data="hjbwSelectedTableData"
              :msiusidppoi="0"
            />
          </a-col>
        </a-row>

        <!--<a-alert type="success" class="mt-5">
          <template #message>
            1.近日百度流量接口出现不稳定情况，导致前端查价出现报错或者不出现推荐关键词的情况，技术已经紧急处理，预计2-3个工作日；<br />
            2.遇到此种情况可以尝试多次点击“查询”触发接口，一般3-5次可以出查询结果。给您带来的不便还请谅解。
          </template>
        </a-alert>-->
      </div>
    </base-container>

    <div v-show="getResult && (BW || BWYXB)">
      <BaseContainer class="mt-5" :show-title="false">
        <HotWordDetail :version-type="versionType" :phoenix-checker="phoenixChecker" :data="bwPriceInfo.wordAskWords" />
      </BaseContainer>
      <BaseContainer class="mt-5" :show-title="false">
        <BwBaidu
          :coordinates-hook="coordinatesHook"
          :price-utils="proPriceUtils"
          :mobile-sold="mobileSold"
          :pc-sold="pcSold"
          :pc-disable="pcDisable"
          :mobile-disable="mobileDisable"
          :bwPriceInfo="bwPriceInfo"
          v-model:creative-select="creativeSelect"
          v-model:qihu360-select="qihu360Select"
          v-model:type="type"
          @cibao-reset="handleCiBaoReset"
          @bw-reset="handleBwReset"
        />
        <BwPremium :premiums="premiums" />
      </BaseContainer>
    </div>

    <div>
      <CbFooter
        v-show="CiBao || CBYXB || CBTEH || WBTEH || DFTEH || DFTEX"
        :submitting="submitting || bwSubmitting"
        :current-package="currentPackage"
        :selected-table-data="selectedTableData"
        :combo-price-id="CiBaoFormFields.comboPriceId"
        :combo-price-list="comboPriceList"
        :platform-ids="platformIds"
        @submit="handleSubmit"
      />
      <!-- 临时调试信息 -->
      <!-- <div
        v-if="CiBao || CBYXB || CBTEH || WBTEH || DFTEH || DFTEX"
        style="
          position: fixed;
          top: 10px;
          right: 10px;
          background: white;
          padding: 10px;
          border: 1px solid #ccc;
          z-index: 1000;
          font-size: 12px;
        "
      >
        <p>当前comboPriceId: {{ CiBaoFormFields.comboPriceId }}</p>
        <p>comboPriceList:</p>
        <ul style="margin: 0; padding-left: 20px">
          <li v-for="item in comboPriceList" :key="item.id">ID: {{ item.id }} - {{ item.info }}</li>
        </ul>
      </div> -->
      <BwFooter
        v-show="getResult && (BW || BWYXB)"
        :btn-text="btnText"
        :total-price="proTotalPrice"
        @submit="handleBwSubmit"
      />
      <HJBWFooter
        v-show="HJBW"
        :submitting="submitting || bwSubmitting"
        :current-package="currentPackage"
        :selected-table-data="hjbwSelectedTableData"
        :marketPrice="marketPrice"
        :comboPrice="HJBWFormFields.comboPrice"
        @submit="handleHjbwSubmit"
      />
    </div>

    <div
      v-if="(DFTEH || CBTEH) && yongjingeu && !WBTEH"
      style="width: 100%; height: 400px; background-color: white; display: flex"
    >
      <!-- <div v-if="comboIdfn != 3" style="margin-left: 15px" @click="yanse()">
        <div
          :style="{ color: dynamicColor, background: dynamColor }"
          style="border-radius: 15px; width: 288px; height: 223px; border: 1px solid red"
        >
          <div style="margin-top: 10px; margin-left: 15px"> -->
      <!-- <p :style="{ color: dynamicColor }">创意升级，效果加倍  </p>  -->
      <!-- <p :style="{ color: yansjis, fontWeight: fonis, fontSize: Sizeis }" class="zhonjianwent">时段加油包</p>
            <p>原价1500元，限时特惠升级7*24小时</p>
            <p :style="{ color: yansjis }" class="zhonjianwent">限时特惠:0元</p> -->
      <!-- <p>原价1500</p>
            <p :style="{ color: yansjis }"  class="zhonjianwent">限时特惠:0元</p>  -->
      <!-- <p>
              投放时长 <br />
              <b> 365天 </b>
            </p>
          </div>
        </div>
      </div> -->
      <!-- v-if="CiBaoFormFields.packageId !== 15 && CiBaoFormFields.packageId !== 16" -->
      <!--      <div-->
      <!--        v-if="CiBaoFormFields.packageId === 4 || CiBaoFormFields.packageId === 9 || CiBaoFormFields.packageId === 20"-->
      <!--        style="margin-left: 15px"-->
      <!--      >-->
      <!--        <div-->
      <!--          style="-->
      <!--            border-radius: 15px;-->
      <!--            width: 300px;-->
      <!--            height: 223px;-->
      <!--            border: 1px solid red;-->
      <!--            background-color: #ff4d4f;-->
      <!--            color: white;-->
      <!--          "-->
      <!--        >-->
      <!--          <div style="margin-top: 10px; margin-left: 15px">-->
      <!--            <p class="zhonjianwent" style="font-weight: 600; font-size: 20px">50词版拓量包</p>-->
      <!--            <p style="font-size: 15px">原价2000元，赠送50个精准关键词拓量</p>-->
      <!--            <p>限时特惠:赠送</p>-->
      <!--            <p class="zhonjianwent">投放时长 365天</p>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->

      <div v-if="!DFTEH && CiBaoFormFields.packageId === 9" style="margin-left: 15px">
        <!-- v-if="CiBaoFormFields.packageId === 4 || CiBaoFormFields.packageId === 9" -->
        <div
          style="
            border-radius: 15px;
            width: 300px;
            height: 223px;
            border: 1px solid red;
            background-color: #ff4d4f;
            color: white;
          "
        >
          <div style="margin-top: 10px; margin-left: 15px">
            <p class="zhonjianwent" style="font-weight: 600; font-size: 20px">精美钻石店铺</p>
            <p style="font-size: 15px">多种工业风店铺主题，多种交互动效，更加贴合企业形象</p>
            <p>原价：600元</p>
            <p class="zhonjianwent">特惠价：300元</p>
          </div>
        </div>
      </div>
      <!--      <div-->
      <!--        style="margin-left: 10px"-->
      <!--        @click="isyanse"-->
      <!--        v-if="-->
      <!--          CiBaoFormFields.packageId !== 15 &&-->
      <!--          CiBaoFormFields.packageId !== 16 &&-->
      <!--          (CiBaoFormFields.packageId < 22 || CiBaoFormFields.packageId > 23)-->
      <!--        "-->
      <!--      >-->
      <!--        <div-->
      <!--          :style="{ color: youciedynamicColor, background: youciedynamColor }"-->
      <!--          style="border-radius: 15px; width: 300px; height: 223px; border: 1px solid red"-->
      <!--        >-->
      <!--          <div style="margin-top: 10px; margin-left: 15px">-->
      <!--            &lt;!&ndash; <p :style="{ color: youciedynamicColor }">-->
      <!--              创意升级，效果加倍</p>   &ndash;&gt;-->
      <!--            <p :style="{ color: yansjisitem, fontWeight: fonis, fontSize: Sizeis }" class="zhonjianwent">精准拓量包</p>-->
      <!--            <p>原价4000元，可享100个精准关键词拓量</p>-->
      <!--            <p :style="{ color: yansjisitem }" class="zhonjianwent">限时特惠:1000元</p>-->
      <!--            <p>-->
      <!--              投放时长-->
      <!--              <br />-->
      <!--              <b>365天</b>-->
      <!--            </p>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
    </div>
  </base-container>
</template>

<script lang="ts" setup>
import { computed, defineOptions, onActivated, onDeactivated, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { compact, intersectionWith, isNil } from 'lodash-es'
import TableToolbar from '@/components/table-toolbar/index.vue'
import getKeywordList, { type CiBaoPriceAskParams } from '@/services/price-sheet/getKeywordList'
import getPackageList, { type PackageData } from '@/services/price-sheet/getPackageList'
import createPriceSheet from '@/services/price-sheet/createPriceSheet'
import { useMainStore } from '@/store/useMainStore'
import { usePriceSheetStore } from '@/store/usePriceSheetStore'
import type { VersionItem } from '@/views/price-sheet/interface'
import { BwComboPriceNameKeyMap, BwVersionTypeKeyMap } from '@/views/price-sheet/interface'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import KeywordTable from '@/views/price-sheet/components/KeywordTable.vue'
import SelectedTable from '@/views/price-sheet/components/SelectedTable.vue'
import BaseContainer from '@/components/base-container/index.vue'
import CbFooter from '@/views/price-sheet/components/CbFooter.vue'
import HJBWFooter from '@/views/price-sheet/components/HJBWFooter.vue'
import BwFooter from '@/views/price-sheet/components/BwFooter.vue'
import HotWordDetail from '@/views/price-sheet/components/HotWordDetail.vue'
import ForbiddenText from '@/views/price-sheet/components/ForbiddenText.vue'
import BwBaidu from '@/views/price-sheet/components/BwBaidu.vue'
import QueryFields from '@/views/price-sheet/components/QueryFields.vue'
import type { BwPriceAskParams } from '@/services/price-sheet/getBwPriceAskWords'
import getBwPriceAskWords from '@/services/price-sheet/getBwPriceAskWords'
import { reactiveComputed } from '@vueuse/core'
import getComboPriceList from '@/services/price-sheet/getComboPriceList'
import Divider from '@/components/divider/index.vue'
import { useCategory } from '@/hooks/useCategotry'
import getPhoenixRegionCheckResult from '@/services/price-sheet/getPhoenixRegionCheckResult'
import type { PhoenixRegionCheckResult } from '@/services/price-sheet/getPhoenixRegionCheckResult'
import { CreativePictureEnum, TypeEnum, VersionTypeEnum, LandingPageEnum, IsFromHjzwEnum } from '@/core/enums/type'
import { ProductEnum } from '@/core/enums/platform'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { PricePlatformKeyMap } from '@/core/mapper/platform'
import { ApproveStatusEnum } from '@/core/enums/status'
import type { VectorX } from '@/core/interfaces/priceTable'
import { DataIndex } from '@/core/enums/name'
import type { Coordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceCoordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceTable } from '@/views/price-sheet/hooks/usePriceTable'
import { useTotalPrice } from '@/views/price-sheet/hooks/useTotalPrice'
import { usePriceSold } from '@/views/price-sheet/hooks/usePriceSold'
import BwPremium from '@/views/price-sheet/components/BwPremium.vue'
import is from '@/utils/is'
import { fromZodError } from 'zod-validation-error'
import { bwPriceDataNormalizer, bwPriceDataParser } from '@/core/parser/priceDataParser'
import { useReloadModal } from '@/hooks/useReloadModal'
import { usePriceDisable } from '@/views/price-sheet/hooks/usePriceDisable'
import { add, toFixed } from '@/utils/math'
import createBwPriceSheet from '@/services/price-sheet/createBwPriceSheet'
import QueryFieldsHJBW from '@/views/price-sheet/components/QueryFieldsHJBW.vue'
import { toLabelValue } from '@/utils'
import { LandingPageMap } from '@/core/mapper/type'
import getKeywordListHjbw from '@/services/price-sheet/getKeywordListHjbw'
import type { HjbwPriceAskParams } from '@/services/price-sheet/getKeywordListHjbw'
import { byteLength } from '@/utils'
import createHjbwPriceSheet from '@/services/price-sheet/createHjbwPriceSheet'
import { ComboPriceNameEnum } from '@/core/enums/name'
import { useRoute } from 'vue-router'
import { TypeCode } from '@/views/price-sheet/price-checking-by-category/type'

const route = useRoute()
const fonis = ref(700)
const Sizeis = ref('20px')
const tasyinchangd = ref(false)
const phoenixChecker = ref<Record<string, PhoenixRegionCheckResult>>({})

const code = computed(() => {
  return route.name
})

const yongjingeu = ref(false)

const dabiaogei = ref(false)
const dabiaogeis = ref(false)

const dynamicColor = ref('white')
const dynamColor = ref('#ff4d4f')
const yansjis = ref('#fff')

const yansjisitem = ref('#ff4d4f')
const youciedynamicColor = ref('black')
const youciedynamColor = ref('white')
const yanse = () => {
  dabiaogei.value = !dabiaogei.value
  if (dabiaogei.value) {
    dynamicColor.value = 'white'
    dynamColor.value = '#ff4d4f'
    yansjis.value = '#fff'
  } else {
    dynamicColor.value = 'black'
    dynamColor.value = 'white'
    yansjis.value = '#ff4d4f'
  }
}
const isyanse = () => {
  dabiaogeis.value = !dabiaogeis.value
  if (dabiaogeis.value) {
    youciedynamicColor.value = 'white'
    youciedynamColor.value = '#ff4d4f'
    yansjisitem.value = 'white'
  } else {
    youciedynamicColor.value = 'black'
    youciedynamColor.value = 'white'
    yansjisitem.value = 'red'
  }
}

const packageCode = ref(1)
const LandingPageList = computed(() => {
  return hjbwSelectedTableData.value?.length < 5
    ? toLabelValue(LandingPageMap).filter((item) => item.value !== 2)
    : toLabelValue(LandingPageMap)
})

defineOptions({
  name: 'PricePackage'
})

useReloadModal()
const router = useRouter()
const mainStore = useMainStore()
const priceSheetStore = usePriceSheetStore()

const loading = computed(() => {
  return keywordLoading.value || hjbwKeywordLoading.value
})

const [, createHjbwPriceSheetFn] = createHjbwPriceSheet()
const [packageList, fetchPackageList] = getPackageList()
const [rawKeywordTableData, fetchKeywordList, keywordLoading] = getKeywordList()
const [rawKeywordTableDataHjbw, getKeywordListHjbwFn, hjbwKeywordLoading] = getKeywordListHjbw()
const [, fetchPriceSheet, submitting] = createPriceSheet()
const [, fetchBwPriceSheet, bwSubmitting] = createBwPriceSheet()
const [bwPriceInfo, fetchBwPriceAskWord] = getBwPriceAskWords()
const [comboPriceList, fetchComboPriceList, comboPriceLoading] = getComboPriceList()
const [phoenixCheckerRes, fetchPhoenixRegionChecker] = getPhoenixRegionCheckResult()

console.log(packageList.value, '是不是直接的值')

// 点击特惠版传过来的id
const handleBwResetiusid = async (data) => {
  // 获取 platformIds（如果需要）
  const getPlatformIdsIfNeeded = () => {
    if (route.name === 'price-package-df') {
      let ids = ''
      if (QueryFieldsRef.value && typeof QueryFieldsRef.value.getPlatformIds === 'function') {
        ids = QueryFieldsRef.value.getPlatformIds()
      }
      if (!ids && platformIds.value) {
        ids = platformIds.value
      }
      if (!ids) {
        ids = '1'
      }
      return ids
    }
    return undefined
  }

  if (data.productId === 7) {
    const [err, res] = await fetchPackageList({
      productId: 7
    })
    fetchComboPriceList({
      comboId: 4,
      platformIds: getPlatformIdsIfNeeded()
    })
  } else {
    const [err, res] = await fetchPackageList({
      productId: data.productId
    })
  }

  if (data.productId === 2) {
    fetchComboPriceList({
      comboId: 3,
      platformIds: getPlatformIdsIfNeeded()
    })
  }

  if (data.productId === 6) {
    fetchComboPriceList({
      comboId: 3,
      platformIds: getPlatformIdsIfNeeded()
    })
  }
}

const versionList = ref<VersionItem[]>([
  {
    title: '标准版',
    desc: '店铺显示商户电话，商户可根据需求自定义电话号码',
    active: true,
    id: VersionTypeEnum.Normal
  },
  {
    title: '普惠版',
    desc: '店铺不显示商户电话，平台400电话转接商户电话',
    active: false,
    id: VersionTypeEnum.Cheap
  },
  {
    title: '高级版',
    desc: '店铺显示商户电话，商户自定义店铺域名',
    active: false,
    id: VersionTypeEnum.Pro
  }
])

const defaultBwFormFields: () => BwPriceAskParams = () => ({
  biaowang: ProductEnum.BW,
  priceAskWords: [],
  serviceAreas: [],
  zzbwOrderNo: '',
  userAreas: [],
  assessmentPricesId: 0
})

const defaultCibaoFormFields: () => CiBaoPriceAskParams = () => ({
  cibao: ProductEnum.CiBao,
  packageId: 4,
  comboPriceId: undefined,
  zzbwOrderNo: '',
  keyword: ''
})

const defaultHJBWFormFields: () => HjbwPriceAskParams = () => ({
  cibao: ProductEnum.HJBW,
  packageId: undefined,
  comboPriceId: undefined,
  comboPriceName: ComboPriceNameEnum.YEAR,
  keyword: undefined,
  onLinePeriod: '7*24',
  shopType: LandingPageEnum.SinglePage,
  comboPrice: undefined,
  hzTransferCode: IsFromHjzwEnum.Yes,
  hzNotes: undefined,
  zzbwOrderNo: ''
})
const marketPrice = ref<number>()

const bwSearching = ref(false)
const getResult = ref(false)
const isActivated = ref(false)
const creativeSelect = ref(false)
const qihu360Select = ref(false)
const QueryFieldsRef = ref<InstanceType<typeof QueryFieldsHJBW>>()
const releaseRange = `${dayjs().add(10, 'day').format('YYYY-MM-DD')}`
const selectedTableData = ref<PriceKeyword[]>([])
const keywordTableData = ref<PriceKeyword[]>([])
const hjbwSelectedTableData = ref<PriceKeyword[]>([])
const hjbwKeywordTableData = ref<PriceKeyword[]>([])
const BwFormFields = ref<BwPriceAskParams>(defaultBwFormFields())
const CiBaoFormFields = ref<CiBaoPriceAskParams>(defaultCibaoFormFields())
const HJBWFormFields = ref<HjbwPriceAskParams>(defaultHJBWFormFields())
const type = ref<ProductEnum>(ProductEnum.CBTEH)
const platformIds = ref<string>('')
// 打印type的值

watch(
  () => code.value,
  (val) => {
    if (val === TypeCode.BW) {
      type.value = ProductEnum.BWYXB
    } else if (val === TypeCode.HJ) {
      type.value = ProductEnum.HJBW
    } else if (val === TypeCode.CB) {
      type.value = ProductEnum.CBYXB
    } else if (val === TypeCode.WB) {
      type.value = ProductEnum.WbBao
    } else if (val === TypeCode.DF) {
      type.value = ProductEnum.CBTEH
    }
  },
  {
    deep: true,
    immediate: true
  }
)
// const type = computed(() => {
//   return code.value === TypeCode.BW ? ProductEnum.BW : code.value === TypeCode.HJ ? ProductEnum.HJBW : ProductEnum.CiBao
// })
const { BW, CiBao, HJBW, BWYXB, CBYXB, CBTEH, WBTEH, DFTEH, DFTEX } = useCategory(type)

const queryFields = reactiveComputed(() => {
  return BW.value || BWYXB.value ? BwFormFields.value : CiBao || CBYXB ? CiBaoFormFields.value : HJBWFormFields.value
})
const versionType = computed(() => {
  return versionList.value.find((v) => v.active)?.id ?? VersionTypeEnum.Normal
})
const assessmentPrices = computed(() => {
  return bwPriceInfo.assessmentPrices
})
const premiums = computed(() => {
  return bwPriceInfo.premiums || []
})
const premiumRatio = computed(() => {
  return premiums.value.reduce((a, b) => {
    return add(a, b.premiumRatio).toNumber()
  }, 1)
})
const morzjos = ref({
  id: 12,
  comboId: 5,
  type: 4,
  info: '年单',
  price: 1000
})
const comboPriceData = computed(() => {
  // 尝试找到匹配的 comboPriceId
  const found = comboPriceList.value.find((c) => c.id === CiBaoFormFields.value.comboPriceId)

  // 如果没有找到匹配的值，或者 CiBaoFormFields.value.comboPriceId 是空的，则返回默认值
  if (!found || !CiBaoFormFields.value.comboPriceId) {
    // 设置默认值，这里假设默认值是 comboPriceList 的第一个项目
    return comboPriceList.value.length > 0 ? comboPriceList.value[0] : morzjos.value
  }

  // 如果找到了匹配的值，则返回该值
  return found

  // return comboPriceList.value.find((c) => c.id === CiBaoFormFields.value.comboPriceId)
})
const hasCreativePicture = computed(() => {
  return creativeSelect.value ? CreativePictureEnum.yes : CreativePictureEnum.no
})

const coordinatesHook = usePriceCoordinates()
const priceUtils = usePriceTable(coordinatesHook, assessmentPrices)
const totalPrice = useTotalPrice(
  priceUtils.currentBaiduPrice,
  priceUtils.current360Price,
  priceUtils.creativePrice,
  creativeSelect,
  qihu360Select
)
const { mobileDisable, pcDisable } = usePriceDisable(bwPriceInfo)
const { mobileSold, pcSold } = usePriceSold(bwPriceInfo, versionType, phoenixChecker, BwFormFields, type.value)
const { currentBaiduPriceData, current360PriceData } = priceUtils
const { resetCoordinates, setBaiduCoordinates, set360Coordinates } = coordinatesHook

const proPriceUtils = usePriceTable(coordinatesHook, assessmentPrices, premiums)
const proTotalPrice = useTotalPrice(
  proPriceUtils.currentBaiduPrice,
  proPriceUtils.current360Price,
  proPriceUtils.creativePrice,
  creativeSelect,
  qihu360Select
)

function defaultCoordinates(): Coordinates {
  if (mobileSold.value && pcSold.value) {
    return []
  }

  if (pcDisable.value && mobileDisable.value) {
    return []
  }

  if (!pcSold.value && !mobileSold.value && !pcDisable.value && !mobileDisable.value) {
    return [0, DataIndex.Platform5x8]
  } else if (pcSold.value || pcDisable.value) {
    return [0, DataIndex.Mobile5x8]
  } else if (mobileSold.value || mobileDisable.value) {
    return [0, DataIndex.Pc5x8]
  } else {
    return []
  }
}

const btnText = computed(() => {
  if (bwPriceInfo.failtureCode) {
    return '提交审核'
  } else {
    return '提交审核'
  }
})
const currentPackage = computed<Partial<PackageData>>(() => {
  return packageList.value.find((p) => p.id === CiBaoFormFields.value.packageId) || {}
})
//
function resetVersionList() {
  versionList.value.forEach((v) => {
    v.active = false
  })
  versionList.value[0].active = true
}

async function handleBwSearcher() {
  getResult.value = false
  bwSearching.value = true
  bwDataReset()
  console.log(BwFormFields.value.priceAskWords, 'BwFormFields.value.priceAskWords')
  if (type.value !== ProductEnum.BWYXB && type.value !== ProductEnum.CBYXB) {
    const [phoenixErr] = await fetchPhoenixRegionChecker({
      keywords: BwFormFields.value.priceAskWords
    })
    if (!phoenixErr) {
      phoenixChecker.value = phoenixCheckerRes.value
    } else {
      bwSearching.value = false
      return message.error(phoenixErr?.message, 5)
    }
  } else {
    phoenixChecker.value = {}
  }

  const [bwErr] = await fetchBwPriceAskWord({ ...BwFormFields.value, productId: type.value })
  if (bwErr) {
    bwSearching.value = false
    return message.error(bwErr?.message, 5)
  }
  bwSearching.value = false
  getResult.value = true

  if (bwPriceInfo.failtureCode) {
    message.warning(bwPriceInfo.msg, 5)
  } else {
    BwFormFields.value.assessmentPricesId = bwPriceInfo.assessmentPricesId
    message.success('关键词已审核通过，确认套餐后可以确认订单~')
  }

  // 这里设置坐标锁定标王百度的格子
  const coordinates = defaultCoordinates()
  setBaiduCoordinates(coordinates)
  set360Coordinates(coordinates)
}
const newproductId = ref('')
async function loadKeywordList(data) {
  console.log(data.productId, '查询套餐', packageList.value)

  if (Object.keys(currentPackage.value).length === 0) {
    message.error('请先选择套餐')
    return
  }
  console.log(CiBaoFormFields.value.packageId, '套餐查询id')

  // Loop through packageList to find the corresponding productId

  const foundPackage = packageList.value.find((pkg) => pkg.id === data.productId)
  console.log(foundPackage, '查询套餐???')

  if (!foundPackage) {
    message.error('未找到对应的套餐')
    return
  }

  if ('cibao' in queryFields) {
    if (!queryFields.keyword) {
      message.error('请输入关键词')
      return
    }

    localStorage.setItem('newproductId', foundPackage.productId)

    // 获取 platformIds，优先使用传递的值，否则从子组件获取当前值
    let platformIdsStr = ''
    if (route.name === 'price-package-df') {
      platformIdsStr = data.platformIds || ''
      console.log('loadKeywordList - 从 data 获取 platformIds:', platformIdsStr)
      // 如果没有传递，从子组件获取当前值
      if (!platformIdsStr && QueryFieldsRef.value) {
        if (typeof QueryFieldsRef.value.getPlatformIds === 'function') {
          platformIdsStr = QueryFieldsRef.value.getPlatformIds()
          console.log('loadKeywordList - 从子组件获取 platformIds:', platformIdsStr)
        } else {
          console.warn('loadKeywordList - getPlatformIds 方法不存在')
        }
      }
      // 如果还是没有，使用保存的值
      if (!platformIdsStr && platformIds.value) {
        platformIdsStr = platformIds.value
        console.log('loadKeywordList - 使用保存的 platformIds:', platformIdsStr)
      }
      // 如果还是没有，设置默认值
      if (!platformIdsStr) {
        platformIdsStr = '1'
        console.log('loadKeywordList - 使用默认值 platformIds:', platformIdsStr)
      }
      // 保存 platformIds 以便后续提交使用
      platformIds.value = platformIdsStr
      console.log('loadKeywordList - 最终使用的 platformIds:', platformIdsStr)
    }

    const [err, res] = await fetchKeywordList({
      keyword: queryFields.keyword,
      productId: foundPackage.productId, // Use the found productId
      comboId: CiBaoFormFields.value.packageId,
      platformIds: platformIdsStr
    })
    if (res.data.code === 0) {
      yongjingeu.value = true
    } else {
      yongjingeu.value = false
    }

    if (!err) {
      intersectionSelectedWord()
    }
  }
}
async function hjbwLoadKeywordList() {
  if (!HJBWFormFields.value.keyword) return message.warning('请输入需要查询的关键词！')
  const len = byteLength(HJBWFormFields.value.keyword)
  if (len < 8) return message.warning('关键词小于8个字节')
  const [err] = await getKeywordListHjbwFn({
    keyword: HJBWFormFields.value.keyword,
    productId: type.value
  })
  if (!err) {
    HjbwIntersectionSelectedWord()
  }
}

function intersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableData.value,
    selectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  keywordTableData.value = rawKeywordTableData.value
}

function HjbwIntersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableDataHjbw.value,
    hjbwSelectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  hjbwKeywordTableData.value = rawKeywordTableDataHjbw.value
}

watch(
  () => hjbwSelectedTableData.value.length,
  (val) => {
    if (val < 5) {
      marketPrice.value = 3680 * val
      HJBWFormFields.value.comboPrice = 2800 * val
      HJBWFormFields.value.shopType = LandingPageEnum.SinglePage
    } else if (val === 5) {
      marketPrice.value = 16800
      HJBWFormFields.value.comboPrice = 12800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 5 && val < 10) {
      marketPrice.value = Number(((16800 / 5) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((12800 / 5) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val === 10) {
      marketPrice.value = 29800
      HJBWFormFields.value.comboPrice = 23800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 10) {
      marketPrice.value = Number(((29800 / 10) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((23800 / 10) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    }
  }
)

function handleCiBaoReset() {
  CiBaoFormFields.value.keyword = ''
  selectedTableData.value = []
  keywordTableData.value = []
  // 如果是视频号页面，重置 platformIds 为默认值（视频号）
  if (route.name === 'price-package-df') {
    platformIds.value = '1'
    // 调用子组件的重置方法
    QueryFieldsRef.value?.handleCibaoReset?.()
  } else {
    platformIds.value = ''
  }
}

function handleHjbwReset() {
  HJBWFormFields.value.keyword = ''
  HJBWFormFields.value.shopType = LandingPageEnum.SinglePage
  hjbwSelectedTableData.value = []
  hjbwKeywordTableData.value = []
}

function handleBwReset() {
  getResult.value = false
  BwFormFields.value = defaultBwFormFields()
  QueryFieldsRef.value?.handleBwReset()
  bwDataReset()
}

function bwDataReset() {
  resetCoordinates()
  resetVersionList()
  creativeSelect.value = false
  qihu360Select.value = false
}

async function loadPackageList() {
  const [err] = await fetchPackageList({
    productId: type.value
  })
  if (!err) {
    CiBaoFormFields.value.packageId = packageList.value[0]?.value

    if (CiBaoFormFields.value.packageId) {
      await handlePackageChange(CiBaoFormFields.value.packageId)
    }
  }
}
const comboIdfn = ref(0)
// 切换套餐
function handlePackageChange(comboId: number) {
  console.log(comboId, '切换套餐')
  comboIdfn.value = comboId
  CiBaoFormFields.value.comboPriceId = undefined

  // 获取 platformIds
  let platformIdsStr = ''
  if (route.name === 'price-package-df') {
    if (QueryFieldsRef.value && typeof QueryFieldsRef.value.getPlatformIds === 'function') {
      platformIdsStr = QueryFieldsRef.value.getPlatformIds()
    }
    if (!platformIdsStr && platformIds.value) {
      platformIdsStr = platformIds.value
    }
    if (!platformIdsStr) {
      platformIdsStr = '1'
    }
    console.log('handlePackageChange - 传递的 platformIds:', platformIdsStr)
  }

  fetchComboPriceList({
    comboId,
    platformIds: platformIdsStr || undefined
  })
}

// 处理平台复选框变化
function handlePlatformIdsChange(ids: string) {
  console.log('handlePlatformIdsChange - 收到 platformIds 变化:', ids)
  platformIds.value = ids
}

const moveUp = ref(1)
const addWord = ref(0)
async function handleSubmit() {
  if (route.path !== '/price-package-wb') {
    if (!queryFields.keyword) {
      message.error(`请最少输入一个业务核心词`)
      return
    }

    if (keywordArray.value.length > 20) {
      message.error(`最多查询20个业务核心词`)
      return
    }

    // 添加推广时长的必选验证
    if (isNil(CiBaoFormFields.value.comboPriceId)) {
      return message.error('请选择推广时长')
    }

    // 获取当前的 platformIds 并传递给查询接口
    let platformIdsStr = ''
    if (route.name === 'price-package-df') {
      if (QueryFieldsRef.value?.getPlatformIds) {
        platformIdsStr = QueryFieldsRef.value.getPlatformIds()
      }
      if (!platformIdsStr && platformIds.value) {
        platformIdsStr = platformIds.value
      }
      if (!platformIdsStr) {
        platformIdsStr = '1' // 默认值
      }
    }
    await loadKeywordList({ productId: CiBaoFormFields.value.packageId, platformIds: platformIdsStr })
    selectedTableData.value = keywordTableData.value
  }

  if (route.name != 'price-package-df') {
    if (isNil(CiBaoFormFields.value.comboPriceId)) {
      return message.error('请选择推广时长')
    }
  }

  if (
    (CiBaoFormFields.value.packageId === 22 || CiBaoFormFields.value.packageId === 23) &&
    (!CiBaoFormFields.value.oldCustomerAllWebOrderNo || CiBaoFormFields.value.oldCustomerAllWebOrderNo.trim() === '')
  ) {
    message.error('请输入订单编号')
    return
  }

  if (dabiaogei.value) {
    moveUp.value = 1
  }
  if (dabiaogeis.value) {
    addWord.value = 1
  }

  const params = {
    comboPriceName: comboPriceData.value?.info,
    comboPriceId: comboPriceData.value?.id ?? 0,
    comboPrice: comboPriceData.value?.premiumPrice ?? 0,
    comboName: currentPackage.value?.comboName!,
    zzbwOrderNo: CiBaoFormFields.value?.zzbwOrderNo!,
    comboId: currentPackage.value?.id!,
    proxyId: mainStore.userInfo!.proxy_id,
    proxyName: mainStore.userInfo!.proxy_name,
    priceAskWords: selectedTableData.value,
    sellerName: mainStore.userInfo!.full_name,
    sellerId: mainStore.userInfo!.id,
    productId: route.name == 'price-package-wb' ? type.value : Number(localStorage.getItem('newproductId')),
    // route.name == 'price-package-wb'
    // Number(localStorage.getItem('newproductId'))  type.value
    areas: '全国',
    type: TypeEnum.NEW,
    versionType: VersionTypeEnum.Normal,
    approveStatus: ApproveStatusEnum.PENDING,
    moveUp: moveUp.value,
    addWord: addWord.value,
    machineExamine: bwPriceInfo.machineExamine,
    // 新增字段
    premiumPrice: comboPriceData.value?.premiumPrice ?? 0,
    premiumRatio: comboPriceData.value?.premiumRatio ?? 0,
    marketPrice: comboPriceData.value?.marketPrice ?? 0
  }

  if (CiBaoFormFields.value.packageId === 22 || CiBaoFormFields.value.packageId === 23) {
    params.oldCustomerAllWebOrderNo = CiBaoFormFields.value.oldCustomerAllWebOrderNo
  }

  // 如果是视频号页面，添加 platformIds 参数
  if (route.name === 'price-package-df') {
    // 始终从子组件获取最新的 platformIds 值，确保获取到用户当前选中的复选框状态
    let ids = ''
    console.log('handleSubmit - 开始获取 platformIds')
    if (QueryFieldsRef.value) {
      if (typeof QueryFieldsRef.value.getPlatformIds === 'function') {
        ids = QueryFieldsRef.value.getPlatformIds()
        console.log('handleSubmit - 从子组件获取 platformIds:', ids)
      } else {
        console.warn('handleSubmit - getPlatformIds 方法不存在，QueryFieldsRef.value:', QueryFieldsRef.value)
      }
    } else {
      console.warn('handleSubmit - QueryFieldsRef.value 为空')
    }
    // 如果从子组件获取不到，则使用保存的值
    if (!ids && platformIds.value) {
      ids = platformIds.value
      console.log('handleSubmit - 使用保存的 platformIds:', ids)
    }
    // 如果还是没有值，设置默认值（至少选择视频号）
    if (!ids) {
      ids = '1'
      console.log('handleSubmit - 使用默认值 platformIds:', ids)
    }
    // 确保 platformIds 有值，即使是默认值也要设置
    params.platformIds = ids
    console.log('handleSubmit - 最终提交的 platformIds:', params.platformIds)
    console.log('handleSubmit - 完整的 params:', params)
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交审核',
    async onOk() {
      const [err] = await fetchPriceSheet(params)
      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: selectedTableData.value,
          CibaoPriceData: {
            comboName: currentPackage.value.comboName,
            comboPriceName: comboPriceData.value.info
          },
          approveStatus: ApproveStatusEnum.PENDING,
          type: type.value
        })

        handleBwReset()
        handleCiBaoReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

async function handleHjbwSubmit() {
  if (isNil(HJBWFormFields.value.areas)) {
    return message.warn('请选择推广地域！')
  }
  if (isNil(HJBWFormFields.value.shopType)) {
    return message.warn('落地页不能为空！')
  }
  if (HJBWFormFields.value.hzTransferCode === IsFromHjzwEnum.Yes && !HJBWFormFields.value.hzNotes) {
    return message.warn('请输入转移备注！')
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交审核吗？',
    async onOk() {
      const [err] = await createHjbwPriceSheetFn({
        hzTransferCode: HJBWFormFields.value.hzTransferCode,
        hzNotes: HJBWFormFields.value.hzNotes,
        comboPriceName: HJBWFormFields.value.comboPriceName,
        comboPriceId: comboPriceData.value?.id ?? 0,
        zzbwOrderNo: CiBaoFormFields.value?.zzbwOrderNo!,
        comboPrice: HJBWFormFields.value?.comboPrice ?? 0,
        proxyId: mainStore.userInfo!.proxy_id,
        proxyName: mainStore.userInfo!.proxy_name,
        priceAskWords: hjbwSelectedTableData.value,
        sellerName: mainStore.userInfo!.full_name,
        sellerId: mainStore.userInfo!.id,
        productId: ProductEnum.HJBW,
        areas: HJBWFormFields.value.areas?.join(',') || '',
        type: TypeEnum.NEW,
        versionType: VersionTypeEnum.Normal,
        approveStatus: ApproveStatusEnum.PENDING,
        onLinePeriod: HJBWFormFields.value.onLinePeriod,
        shopType: HJBWFormFields.value.shopType,
        machineExamine: 0
      })

      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: hjbwSelectedTableData.value,
          HjbwPriceData: {
            comboPriceName: HJBWFormFields.value.comboPriceName as unknown as ComboPriceNameEnum
          },
          approveStatus: ApproveStatusEnum.PENDING,
          type: ProductEnum.HJBW
        })

        handleBwReset()
        handleCiBaoReset()
        handleHjbwReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

function getBwComboName() {
  return compact([
    currentBaiduPriceData.value.dataIndex && '百度标王',
    creativeSelect.value && '创意配图',
    qihu360Select.value && '360标王',
    BwVersionTypeKeyMap[versionType.value],
    '标准版钻石店铺',
    ...premiums.value.map((item) => {
      return item.premiumName
    })
  ]).join(' | ')
}

async function handleBwSubmit() {
  const normalizeData = bwPriceDataNormalizer(
    BwFormFields.value,
    bwPriceInfo,
    currentBaiduPriceData.value,
    current360PriceData.value,
    hasCreativePicture.value,
    getBwComboName(),
    versionType.value,
    qihu360Select.value,
    totalPrice.value,
    pcSold.value,
    mobileSold.value,
    premiumRatio.value,
    proTotalPrice.value,
    type.value
  )

  if (is.boolean(normalizeData)) return false

  const valid = bwPriceDataParser().safeParse(normalizeData)
  if (!valid.success) {
    return message.error(fromZodError(valid.error).message)
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交吗？',
    async onOk() {
      const [err] = await fetchBwPriceSheet({
        ...normalizeData,
        machineExamine: bwPriceInfo.machineExamine || 0,
        costRate: bwPriceInfo.costRate
      })

      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: normalizeData.priceAskWords,
          approveStatus: normalizeData.approveStatus,
          BwPriceData: {
            quote: currentBaiduPriceData.value.quote as VectorX['quote'],
            comboPriceName: BwComboPriceNameKeyMap[currentBaiduPriceData.value.timer!],
            columnName: PricePlatformKeyMap[currentBaiduPriceData.value.columnName!],
            hasCreativePicture: hasCreativePicture.value,
            versionType: versionType.value
          },
          Bw360PriceData: qihu360Select.value
            ? {
                quote: current360PriceData.value.quote!,
                comboPriceName: BwComboPriceNameKeyMap[current360PriceData.value.timer!],
                columnName: PricePlatformKeyMap[current360PriceData.value.columnName!]
              }
            : undefined,
          type: type.value
        })

        handleBwReset()
        handleCiBaoReset()
        handleHjbwReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}
// async function jjis() {
//   const [err, res] = await fetchPackageList({
//     productId: 9
//   })
// }

onMounted(() => {
  loadPackageList()
  // jjis()
})

onActivated(() => {
  isActivated.value = true
})

onDeactivated(() => {
  isActivated.value = false
})

const keywordArray = computed(() => {
  return queryFields.keyword
    .toLowerCase()
    .split(/[\n\r\s,，;；]+/g)
    .filter((t) => t !== '')
})
</script>

<style scoped lang="scss">
.toolbar {
  width: 700px;

  &-keyword {
    max-width: 326px;
    min-width: 250px;
  }

  &-local {
    padding-top: 5px;
    padding-bottom: 5px;
  }
}

.search-icon {
  color: #a6a6a6;
}
</style>
